<template>
  <div class="givePrescri pl-30">
    <div class="text-center ptb-30">
      <el-radio-group v-model="radio">
        <el-radio-button label="中药"></el-radio-button>
        <el-radio-button label="西药"></el-radio-button>
      </el-radio-group>
    </div>
    <div class="content pt-35 plr-20">
      <p class="c6 fz-36 mb-10" style="padding-left: 108px">RP</p>

      <template v-if="radio == '中药'">
        <el-form :model="cnForm" :rules="cnRules" ref="cnFormRef">
          <el-form-item label="疾病名称" label-width="108px" prop="DiseaseName">
            <el-input
              v-model="cnForm.DiseaseName"
              placeholder="请输入疾病名称"
            />
          </el-form-item>
          <el-form-item label="购买量" label-width="108px" prop="Count">
            <el-input
              v-model="cnForm.Count"
              type="number"
              placeholder="请输入购买量"
            />
          </el-form-item>
          <el-form-item label="中药名" label-width="108px" prop="CNCode">
            <!-- <el-input v-model="cnForm.CNCode" placeholder="请输入中药名" /> -->
            <el-select
              v-model="cnForm.CNCode"
              filterable
              placeholder="请选择药品"
            >
              <el-option
                v-for="item in curOptList"
                :key="item.CNCode"
                :label="item.value"
                :value="item.CNCode"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="处方描述" label-width="108px">
            <el-input
              v-model="cnForm.prescription_desc"
              :autosize="{ minRows: 6, maxRows: 12 }"
              type="textarea"
              placeholder=""
            >
            </el-input>
          </el-form-item>
          <div class="flex flex-center pb-10">
            <el-button type="primary" class="footer-btn" @click="onSubmit"
              >生成订单</el-button
            >
          </div>
        </el-form>
      </template>
      <template v-else>
        <el-form :model="westForm" ref="westFormRef">
          <el-form-item
            label="疾病名称"
            label-width="108px"
            prop="DiseaseName"
            :rules="{
              required: true,
              message: '请输入疾病名称',
              trigger: 'blur'
            }"
          >
            <el-input v-model="DiseaseName" placeholder="请输入疾病名称" />
          </el-form-item>
          <template v-for="(item, index) in westForm.westFormList" :key="index">
            <el-form-item
              label="药品通用名"
              label-width="108px"
              :prop="'westFormList.' + index + '.DrugId'"
              :rules="{
                required: true,
                message: '药品通用名不能为空',
                trigger: 'blur'
              }"
            >
              <el-select
                v-model="item.DrugId"
                filterable
                placeholder="请选择药品"
              >
                <el-option
                  v-for="info in wesoptoList"
                  :key="info.DrugId"
                  :label="info.value"
                  :value="info.DrugId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="购买量"
              label-width="108px"
              :prop="'westFormList.' + index + '.Count'"
              :rules="{
                required: true,
                message: '购买量不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.Count"
                type="number"
                placeholder="请输入购买量"
              />
            </el-form-item>
            <el-form-item
              label="单位"
              label-width="108px"
              placeholder="请输入单位（盒，瓶）"
              :prop="'westFormList.' + index + '.CountUnit'"
              :rules="{
                required: true,
                message: '请输入单位（盒，瓶）',
                trigger: 'blur'
              }"
            >
              <el-input v-model="item.CountUnit" placeholder="单位" />
            </el-form-item>
          </template>
          <el-form-item label="处方描述" label-width="108px">
            <el-input
              v-model="prescription_desc"
              :autosize="{ minRows: 6, maxRows: 12 }"
              type="textarea"
              placeholder=""
            >
            </el-input>
          </el-form-item>
          <div
            class="flex flex-center flex-align-center cp c-active"
            style="margin-bottom: 53px"
            @click="addItem"
          >
            <p class="add flex flex-center mr-6">
              <img src="@/assets/img/icon/add.svg" alt="" />
            </p>
            添加更多
          </div>
          <div class="flex flex-center pb-10">
            <el-button type="primary" class="footer-btn" @click="onSubmit1"
              >生成订单</el-button
            >
          </div>
        </el-form>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import {
  ConsultWestMedicine,
  ConsultCnMedicine,
  ConsultCNSaveInquiry,
  ConsultSaveInquiry
} from '@/service/api/doctor'
import { cnRules } from '../config/rules'
import { ElMessage } from 'element-plus'
import { ElForm } from 'element-plus'
export default defineComponent({
  name: 'givePrescri',
  setup() {
    const store = useStore()
    const route = useRoute()
    const cnFormRef = ref<InstanceType<typeof ElForm>>()
    const westFormRef = ref<InstanceType<typeof ElForm>>()
    const curOptList = ref([]) // 中药
    const wesoptoList = ref([]) // 西药
    const i = route.params.i as string | number
    let radio = ref('中药')

    const state = reactive({
      cnForm: {
        DiseaseName: '', //疾病名称
        Count: '', // 用量，required
        CNCode: '', //中药编码，required
        CNDrugsName: '', //中药名称
        prescription_desc: ''
      },
      DiseaseName: '', //疾病名称
      prescription_desc: '', //西药处方描述
      westForm: {
        westFormList: [
          {
            CommonName: '', // 药品通用名
            DrugId: '', //药品id
            // Spec: '', //规格
            Count: '', //购买量
            CountUnit: '' // 购买单位 盒，瓶
            // DrugName: '', //药品编码
            // roducer: '', // 生产厂家
            // ApprovalNo: '' //批准文号
          }
        ]
      }
    })
    const addItem = () => {
      let item = {
        CommonName: '', // 药品通用名required
        DrugId: '', //药品id
        // Spec: '', //规格required
        Count: '', //购买量required
        CountUnit: '' // 购买单位 盒，瓶required
        // DrugName: '', //药品编码
        // roducer: '', // 生产厂家
        // ApprovalNo: '' //批准文号 required
      }
      state.westForm.westFormList.push(item)
    }
    const onSubmit = () => {
      if (store.state.user.clientInfo.ua_id) {
        return ElMessage.error('该用户未预约，无法开处方')
      }
      cnFormRef.value?.validate((valid) => {
        if (valid) {
          console.log('验证成功')
          let postData = {
            i: i,
            UserId: store.state.user.userInfo.id,
            PatientId: store.state.user.clientInfo.patient_id,
            appointment_id: store.state.user.clientInfo.ua_id,
            ...state.cnForm
          }
          ConsultCNSaveInquiry(postData).then((res) => {
            if (res.code == 200) {
              ElMessage.success(res.data.msg)
            }
          })
        }
      })
    }
    const onSubmit1 = () => {
      if (store.state.user.clientInfo.ua_id) {
        return ElMessage.error('该用户未预约，无法开处方')
      }
      westFormRef.value?.validate((valid) => {
        if (valid) {
          console.log('1验证成功')
          let postData = {
            i: i,
            UserId: store.state.user.userInfo.id,
            PatientId: store.state.user.clientInfo.patient_id,
            DiseaseName: state.DiseaseName,
            prescription_desc: state.prescription_desc,
            appointment_id: store.state.user.clientInfo.ua_id,
            DrugsInfos: state.westForm.westFormList
          }
          ConsultSaveInquiry(postData).then((res) => {
            if (res.code == 200) {
              ElMessage.success(res.data.msg)
            }
          })
        }
      })
    }
    const ajaxGetData = () => {
      ConsultCnMedicine().then((res) => {
        curOptList.value = res.data.map(
          (v: { CNDrugsName: string; CNCode: string }) => ({
            value: v.CNDrugsName,
            CNCode: v.CNCode
          })
        )
      })
      ConsultWestMedicine().then((res) => {
        wesoptoList.value = res.data.map(
          (v: { DrugName: string; DrugId: number }) => ({
            value: v.DrugName,
            DrugId: v.DrugId
          })
        )
        // LocalCache.setCache('wesoptoList', this.wesoptoList)
      })
    }

    onMounted(() => {
      ajaxGetData()
    })
    return {
      ...toRefs(state),
      cnRules,
      radio,
      addItem,
      onSubmit,
      onSubmit1,
      curOptList,
      wesoptoList,
      cnFormRef,
      westFormRef
    }
  }
})
</script>

<style lang="less" scoped>
.givePrescri {
  .add {
    width: 26px;
    height: 26px;
    border-radius: 100px;
    background-color: #679aff;
    font-size: 26px;
    img {
      width: 12px;
    }
  }
  :deep(.el-select) {
    width: 100%;
  }
}
</style>
